//
//  SettingSystemViewController.m
//  TodaysPlan
//
//  Created by 寺田 篤史 on 11/11/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "SettingSystemViewController.h"
#import "ConfigManager.h"

//#import "ConfigManager.h"

#define TASK_TAG @"task"
#define PRIORITY_TAG @"priority"

@implementation SettingSystemViewController
@synthesize keys_;
@synthesize dataSource_;

- (id)init{
    //ナビゲーションバーにボタンを追加
    UIBarButtonItem *closeButton = [[[UIBarButtonItem alloc]
                                    initWithTitle:NSLocalizedString(@"closeButton", "close button name")
                                    style:UIBarButtonItemStylePlain
                                    target:self
                                    action:@selector(closeAddTodaysPlan:)
                                    ] autorelease];
    self.navigationItem.leftBarButtonItem = closeButton;

    return self;
}
- (void)loadView{
    [super loadView];
    self.navigationController.title = NSLocalizedString(@"settingsTitle", "settings title");    
    self.tableView = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
    keys_ =[[NSArray alloc] initWithObjects:@"header",@"detail",nil];
    NSArray *object1 = [NSArray arrayWithObjects:@"priority_H",@"priority_M",@"priority_L",nil];
    NSArray *object2 = [NSArray arrayWithObjects:@"APNS",nil];
    NSArray *objects = [NSArray arrayWithObjects:object1,object2,nil];
    dataSource_ = [[NSDictionary alloc] initWithObjects:objects forKeys:keys_];    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (NSDate *)setLabelData:(NSDate *)date{
    return date;
}
#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [keys_ count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    id key = [keys_ objectAtIndex:section];
    return [[dataSource_ objectForKey:key] count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    cell.backgroundColor = [UIColor whiteColor];
    //priority color
    if(indexPath.section == 0){
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if(indexPath.row == 0){
            cell.textLabel.text = NSLocalizedString(@"priority_H","priority high color");
            
            UISegmentedControl *prioritySegmentedControl = [[[UISegmentedControl alloc] initWithFrame:CGRectMake(170, 5, 125, 35)] autorelease];
            [prioritySegmentedControl insertSegmentWithTitle:NSLocalizedString(@"priority_red","priority red") atIndex:0 animated:NO];
            [prioritySegmentedControl insertSegmentWithTitle:NSLocalizedString(@"priority_blue","priority blue") atIndex:1 animated:NO];
            [prioritySegmentedControl insertSegmentWithTitle:NSLocalizedString(@"priority_green","priority green") atIndex:2 animated:NO];

            //[self changeSegmentLabelProperty:prioritySegmentedControl];
            ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
            prioritySegmentedControl.selectedSegmentIndex = [[config.cfgPriority_H getValueString] intValue];
            
            [prioritySegmentedControl addTarget:self action:@selector(segmentActionH:) forControlEvents:UIControlEventValueChanged];            
            [cell addSubview: prioritySegmentedControl];
        }
        else if(indexPath.row == 1){
            cell.textLabel.text = NSLocalizedString(@"priority_M","priority middle color");
            
            UISegmentedControl *prioritySegmentedControl = [[[UISegmentedControl alloc] initWithFrame:CGRectMake(170, 5, 125, 35)] autorelease];
            [prioritySegmentedControl insertSegmentWithTitle:NSLocalizedString(@"priority_red","priority red") atIndex:0 animated:NO];
            [prioritySegmentedControl insertSegmentWithTitle:NSLocalizedString(@"priority_blue","priority blue") atIndex:1 animated:NO];
            [prioritySegmentedControl insertSegmentWithTitle:NSLocalizedString(@"priority_green","priority green") atIndex:2 animated:NO];
            
            //[self changeSegmentLabelProperty:prioritySegmentedControl];
            ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
            prioritySegmentedControl.selectedSegmentIndex = [[config.cfgPriority_M getValueString] intValue];
            
            [prioritySegmentedControl addTarget:self action:@selector(segmentActionM:) forControlEvents:UIControlEventValueChanged];
            [cell addSubview: prioritySegmentedControl];
        }
        else if(indexPath.row == 2){
            cell.textLabel.text = NSLocalizedString(@"priority_L","priority low color");

            UISegmentedControl *prioritySegmentedControl = [[[UISegmentedControl alloc] initWithFrame:CGRectMake(170, 5, 125, 35)] autorelease];
            [prioritySegmentedControl insertSegmentWithTitle:NSLocalizedString(@"priority_red","priority red") atIndex:0 animated:NO];
            [prioritySegmentedControl insertSegmentWithTitle:NSLocalizedString(@"priority_blue","priority blue") atIndex:1 animated:NO];
            [prioritySegmentedControl insertSegmentWithTitle:NSLocalizedString(@"priority_green","priority green") atIndex:2 animated:NO];
            
            //[self changeSegmentLabelProperty:prioritySegmentedControl];
            ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
            prioritySegmentedControl.selectedSegmentIndex = [[config.cfgPriority_L getValueString] intValue];
            
            [prioritySegmentedControl addTarget:self action:@selector(segmentActionL:) forControlEvents:UIControlEventValueChanged];
            [cell addSubview: prioritySegmentedControl];
        }
        /*
        cell.detailTextLabel.text = NSLocalizedString(@"taskdetail","task detail");
        cell.selectionStyle = UITableViewCellEditingStyleNone;
        UITextField *taskTextField = [[[UITextField alloc] initWithFrame:CGRectMake(20,10,280,25)] autorelease];
        //taskTextField.text = todaysplan.task;
        ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
        taskTextField.text = [config.cfgTaskData getValueString];
        taskTextField.textAlignment = UITextAlignmentLeft;
        taskTextField.keyboardType = UIKeyboardTypeDefault;
        taskTextField.returnKeyType = UIReturnKeyDone;
        taskTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        taskTextField.delegate = self;
        //[taskTextField becomeFirstResponder];
        taskTextField.tag = 0;
        [cell addSubview:taskTextField];
        */
    }
    else if(indexPath.section == 1){
        //APNS on/off
        cell.textLabel.text = NSLocalizedString(@"apns","apns text");
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
        UISwitch *sw = [[[UISwitch alloc] init] autorelease];
        sw.center = CGPointMake(255, 22.5);
        BOOL isDisp = [config.cfgAPNS getValueBool];
        sw.on = isDisp;
        [sw addTarget:self action:@selector(switchAction:)
        forControlEvents:UIControlEventValueChanged];
        [cell addSubview:sw];
        
        
        
        
        
        
        /*
        if(indexPath.row == 0){
            cell.textLabel.text = NSLocalizedString(@"memo","memo text");
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
            UILabel *reminderDateLabel = [[[UILabel alloc] initWithFrame:CGRectMake(155.0, 12.0, 100.0, 25.0)] autorelease];
            //reminderDateLabel.text = todaysplan.memo;
            ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
            reminderDateLabel.text = [config.cfgMemoData getValueString];
            reminderDateLabel.textAlignment = UITextAlignmentLeft;
            reminderDateLabel.font = [UIFont systemFontOfSize: [UIFont systemFontSize]];
            reminderDateLabel.textColor = [UIColor darkGrayColor];
            [cell.contentView addSubview: reminderDateLabel];
        }
        //priority
        else if(indexPath.row == 1){
            cell.textLabel.text = NSLocalizedString(@"priority","priority text");
            UISegmentedControl *prioritySegmentedControl = [[[UISegmentedControl alloc] initWithFrame:CGRectMake(170, 5, 125, 35)] autorelease];
            //prioritySegmentedControl.tag = PRIORITY_TAG;
            [prioritySegmentedControl insertSegmentWithTitle:NSLocalizedString(@"priorityL","priority Low index text") atIndex:0 animated:NO];
            [prioritySegmentedControl insertSegmentWithTitle:NSLocalizedString(@"priorityM","priority Middle index text") atIndex:1 animated:NO];
            [prioritySegmentedControl insertSegmentWithTitle:NSLocalizedString(@"priorityH","priority High text") atIndex:2 animated:NO];
            //prioritySegmentedControl.selectedSegmentIndex = [todaysplan.priority intValue];
            ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
            prioritySegmentedControl.selectedSegmentIndex = [[config.cfgPriority getValueString] intValue];
            [prioritySegmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
            [cell addSubview: prioritySegmentedControl];
        }
        //reminder
        else if(indexPath.row == 2){
            cell.textLabel.text = NSLocalizedString(@"reminder","reminder text");
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
            UISwitch *sw = [[[UISwitch alloc] init] autorelease];
            sw.center = CGPointMake(255, 22.5);
            BOOL isDisp = [config.cfgReminder getValueBool];
            sw.on = isDisp;
            [sw addTarget:self action:@selector(switchAction:)
            forControlEvents:UIControlEventValueChanged];
            [cell addSubview:sw];
        }
        //reminderDate
        else if(indexPath.row == 3){
            cell.textLabel.text = NSLocalizedString(@"reminderDate","reminderDate text");
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
            ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
            //if(todaysplan.reminderDate !=nil){
            if([config.cfgReminderDate getValueString] != nil){
                UILabel *reminderDateLabel = [[[UILabel alloc] initWithFrame:CGRectMake(155.0, 12.0, 100.0, 25.0)] autorelease];
                NSDateFormatter *inDateFormatter = [[NSDateFormatter alloc] init];
                [inDateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
                //NSString *inputDateStr = todaysplan.reminderDate;
                NSString *inputDateStr = [config.cfgReminderDate getValueString];
                NSDate *inputDate = [inDateFormatter dateFromString:inputDateStr];	
                NSString *reminderDate = [NSDateFormatter localizedStringFromDate:inputDate
                                                                        dateStyle:NSDateFormatterNoStyle
                                                                        timeStyle:NSDateFormatterShortStyle];    
                
                reminderDateLabel.text = reminderDate;
                reminderDateLabel.textAlignment = UITextAlignmentRight;
                reminderDateLabel.font = [UIFont systemFontOfSize: [UIFont systemFontSize]];
                reminderDateLabel.textColor = [UIColor darkGrayColor];
                [inDateFormatter release];
                [cell.contentView addSubview: reminderDateLabel];
            }
            else{
                cell.detailTextLabel.text = NSLocalizedString(@"reminderdetail", "reminder detail");
            }
        }
         */
    }
    return cell;
}    
- (void)textFieldShouldReturn:(UITextField *)tf {
	if( [tf canResignFirstResponder] ) [tf resignFirstResponder];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	NSString *ret = nil;
	
	switch (section) {
		case 0:
			ret = NSLocalizedString(@"colorsettingdetail","priority low color");
			break;
		default:
			break;
	}
	
	return ret;
}

- (void) changeSegmentLabelProperty:(UISegmentedControl *)segmentedControl
{
    int i = 0 ;
	// 各セグメント
	for (id segment in [segmentedControl subviews]) {
		// 各セグメントのラベル
		for (id label in [segment subviews]) {
			if ([label isKindOfClass:[UILabel class]]) {
				// フォントサイズ変更
				//[label setFont:[UIFont boldSystemFontOfSize:12]];
				// フォント色変更
				if (i == 0) {
                    [label setTextColor:[UIColor redColor]];
                }
                else if (i == 1){
                    [label setTextColor:[UIColor blueColor]];
                }
                else if (i == 2){
                    [label setTextColor:[UIColor greenColor]];
                }
                i++;
				// 左詰めにされるので、中心へ変更
				[label setTextAlignment:UITextAlignmentCenter];
			}
		}			
	}
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        //task
        case 0:
        {
            
        }
            break;
        //memo priority reminder
        case 1:
        {
            //memo
            if(indexPath.row == 0){
                //TodaysPlanMemoViewController *vc = [[[TodaysPlanMemoViewController alloc] init] autorelease];
                //[self.navigationController pushViewController:vc animated:YES];
            }
            //reminder
            else if(indexPath.row == 3){
                //DatePickerViewController *vc = [[[DatePickerViewController alloc] init] autorelease];;
                //[vc setDelegate:self];
                //[self.navigationController pushViewController:vc animated:YES];
            }
        }
            break;
        default:
            break;
    }
}
- (void)segmentActionH:(UISegmentedControl*)sender
{
    ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
    [config.cfgPriority_H setValueString:[NSString stringWithFormat:@"%d", sender.selectedSegmentIndex]];
}
- (void)segmentActionM:(UISegmentedControl*)sender
{
    ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
    [config.cfgPriority_M setValueString:[NSString stringWithFormat:@"%d", sender.selectedSegmentIndex]];
}
- (void)segmentActionL:(UISegmentedControl*)sender
{
    ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
    [config.cfgPriority_L setValueString:[NSString stringWithFormat:@"%d", sender.selectedSegmentIndex]];
}
- (void)switchAction:(UISwitch*)sender
{
    ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
    [config.cfgAPNS setValueBool:sender.on];    
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.tag == 0 ) {
        ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
        [config.cfgTaskData setValueString:textField.text];
    }
}
#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
- (void)closeAddTodaysPlan:(id)sender{
    [self dismissModalViewControllerAnimated:YES];
}
- (void)dealloc{
    [keys_ release];
    [dataSource_ release];
    [super dealloc];
}
@end
